package com.evan.review.anr;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ScrollView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

import com.evan.review.R;

/**
 * 广播超时ANR示例Activity
 * 演示广播接收器执行耗时操作导致的ANR
 */
public class BroadcastTimeoutActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "BroadcastTimeoutANR";
    private static final String ACTION_NORMAL_BROADCAST = "com.evan.review.anr.NORMAL_BROADCAST";
    private static final String ACTION_ORDERED_BROADCAST = "com.evan.review.anr.ORDERED_BROADCAST";
    
    private Button btnSendNormalBroadcast; // 发送普通广播按钮
    private Button btnSendOrderedBroadcast; // 发送有序广播按钮
    private TextView tvLogger; // 日志文本框
    private ScrollView svLogger; // 日志滚动视图
    
    private ANRBroadcastReceiver anrBroadcastReceiver; // ANR广播接收器
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_broadcast_timeout);
        
        initViews(); // 初始化视图
        setListeners(); // 设置监听器
        registerBroadcastReceiver(); // 注册广播接收器
        
        logMessage("提示：点击按钮将发送广播，接收器将执行耗时操作并引发ANR");
        logMessage("广播ANR时间阈值：前台广播10秒、后台广播60秒");
    }
    
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播接收器
        if (anrBroadcastReceiver != null) {
            unregisterReceiver(anrBroadcastReceiver);
            anrBroadcastReceiver = null;
        }
    }
    
    /**
     * 初始化视图组件
     */
    private void initViews() {
        btnSendNormalBroadcast = findViewById(R.id.btn_send_normal_broadcast);
        btnSendOrderedBroadcast = findViewById(R.id.btn_send_ordered_broadcast);
        tvLogger = findViewById(R.id.tv_logger);
        svLogger = findViewById(R.id.sv_logger);
    }
    
    /**
     * 设置监听器
     */
    private void setListeners() {
        btnSendNormalBroadcast.setOnClickListener(this);
        btnSendOrderedBroadcast.setOnClickListener(this);
    }
    
    /**
     * 注册广播接收器
     */
    private void registerBroadcastReceiver() {
        anrBroadcastReceiver = new ANRBroadcastReceiver();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_NORMAL_BROADCAST);
        intentFilter.addAction(ACTION_ORDERED_BROADCAST);
        registerReceiver(anrBroadcastReceiver, intentFilter);
        
        logMessage("已注册广播接收器");
    }
    
    @Override
    public void onClick(View v) {
        int id = v.getId();
        
        if (id == R.id.btn_send_normal_broadcast) {
            logMessage("发送普通广播...");
            sendNormalBroadcast();
        } else if (id == R.id.btn_send_ordered_broadcast) {
            logMessage("发送有序广播...");
            sendOrderedBroadcast();
        }
    }
    
    /**
     * 发送普通广播
     */
    private void sendNormalBroadcast() {
        Intent intent = new Intent(ACTION_NORMAL_BROADCAST);
        intent.putExtra("timestamp", System.currentTimeMillis());
        sendBroadcast(intent);
    }
    
    /**
     * 发送有序广播
     */
    private void sendOrderedBroadcast() {
        Intent intent = new Intent(ACTION_ORDERED_BROADCAST);
        intent.putExtra("timestamp", System.currentTimeMillis());
        sendOrderedBroadcast(intent, null);
    }
    
    /**
     * 记录日志信息到界面
     */
    private void logMessage(String message) {
        Log.d(TAG, message);
        
        runOnUiThread(() -> {
            String currentText = tvLogger.getText().toString();
            String newText = currentText + "\n" + message;
            tvLogger.setText(newText);
            
            // 滚动到底部
            svLogger.post(() -> svLogger.fullScroll(View.FOCUS_DOWN));
        });
    }
    
    /**
     * ANR广播接收器实现
     * 在onReceive中执行耗时操作超过10秒，触发ANR
     */
    private class ANRBroadcastReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            long timestamp = intent.getLongExtra("timestamp", 0);
            long currentTime = System.currentTimeMillis();
            long delay = currentTime - timestamp;
            
            logMessage("接收到广播：" + action);
            logMessage("广播传递延迟：" + delay + " 毫秒");
            
            if (ACTION_NORMAL_BROADCAST.equals(action)) {
                logMessage("普通广播开始执行耗时操作，将持续15秒...");
                // 执行耗时操作，超过10秒将导致ANR
                // 前台广播ANR阈值为10秒
                SystemClock.sleep(15000); // 睡眠15秒，确保超过ANR阈值
                logMessage("普通广播耗时操作完成（如果看到此日志，说明ANR未被处理）");
            }
            else if (ACTION_ORDERED_BROADCAST.equals(action)) {
                logMessage("有序广播开始执行耗时操作，将持续15秒...");
                // 执行耗时操作，超过10秒将导致ANR
                SystemClock.sleep(15000); // 睡眠15秒，确保超过ANR阈值
                logMessage("有序广播耗时操作完成（如果看到此日志，说明ANR未被处理）");
            }
        }
    }
} 